﻿using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace MC.Warehouse.Core
{
    static public class SerializeHelper
    {
        //Michael White, Holly Springs Consulting, 2009
        //michael@hollyspringsconsulting.com

        public static T DeserializeXml<T>(string xmlData)
            where T : new()
        {
            if (string.IsNullOrEmpty(xmlData))
                return default(T);
            TextReader tr = new StringReader(xmlData);
            var docItms = new T();
            var xms = new XmlSerializer(docItms.GetType());
            docItms = (T)xms.Deserialize(tr);
            return docItms;
        }

        public static string SeralizeObjectToXml<T>(T xmlObject)
        {
            var sbTr = new StringBuilder();

            var xmsTr = new XmlSerializer(xmlObject.GetType());

            var xwsTr = new XmlWriterSettings();

            var xmwTr = XmlWriter.Create(sbTr, xwsTr);

            xmsTr.Serialize(xmwTr, xmlObject);

            return sbTr.ToString();

        }

        public static T CloneObject<T>(T objClone)
            where T : new()
        {

            var getString = SeralizeObjectToXml(objClone);

            return DeserializeXml<T>(getString);

        }
    }
}
